package com.huaxin.common.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import com.huaxin.common.Global;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * File操作
 */

public class HxFileUtil {
    private static final String TAG                    = "HxFileUtil";
    private static       String DEFAULT_DISK_CACHE_DIR = "takephoto_cache";

    public static File getPhotoCacheDir(Context context, File file, int width, int height) {
        File cacheDir = context.getExternalCacheDir();
       // new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
        String imgName = Global.getUser().getUserId()+"_"+System.currentTimeMillis()+ ".png";


        if (cacheDir != null) {
            File mCacheDir = new File(cacheDir, DEFAULT_DISK_CACHE_DIR);
            if (!mCacheDir.mkdirs() && (!mCacheDir.exists() || !mCacheDir.isDirectory())) {
                return file;
            } else {
                return new File(mCacheDir, imgName);
            }
        }
        if (Log.isLoggable(TAG, Log.ERROR)) {
            Log.e(TAG, "default disk cache dir is null");
        }
        return file;
    }


    /**
     * @desc 清理文件
     * @author songxf
     * created at 2017/8/1 15:07
     */
    public static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    /**
     * 位图转文件
     */
    /**
     * @desc 把bitmap转成File
     * @author songxf
     * created at 2017/8/1 15:11
     */
    public static File bitmapToFile(Bitmap bm, String cachePath, String fileName) {
        try {
            String path = cachePath;
            File dirFile = new File(cachePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            File myCaptureFile = new File(path, fileName);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            return myCaptureFile;
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }
}
